#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <queue>

#include "Thread.hpp"
#include "LockGuard.hpp"
using namespace ThreadMoudle;

static const int gdefaultnum = 5;

// void test()
// {
//     while(true)
//     {
//         ;
//     }
// }

template <typename T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void unLockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }
    void WakeUpAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    bool IsEmpty()
    {
        return _task_queue.empty();
    }
    void HandlerTask(std::string &name)
    { // 领取任务
        while (true)
        {
            //LOG(DEBUG, "%s 开始领取任务\n", name.c_str());
            LockQueue();
            while (IsEmpty() && _isrunning)
            {
                _sleep_thread_num++;
                Sleep();
                _sleep_thread_num--;
            }
            if (IsEmpty() && !_isrunning)
            {
                unLockQueue();
                break;
            }
            // 有任务
            T t = _task_queue.front();
            _task_queue.pop();
            unLockQueue();
            // 执行任务
            // std::cout << name << " get a task:" << t.debug() << std::endl;
            // LOG(DEBUG, "执行任务\n");
            t();
            //LOG(DEBUG, "%s 完成任务\n", name.c_str());
            // std::cout << name << " complete a task:" << t.result() << std::endl;
        }
    }
    void Init()
    {
        func_t func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++)
        {
            std::string threadname = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(threadname, func); // 创造线程池并通过HandlerTask领取任务
        }
    }
    void Start()
    {
        _isrunning = true;
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }
    ThreadPool(int thread_num = gdefaultnum) : _thread_num(thread_num), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T> &tp) = delete;
    void operator()(const ThreadPool<T> &tp) = delete;

public:
    static ThreadPool<T> *getInstance()
    {

        if (_tp == nullptr)
        {
            LockGuard sig_guard(&_sig_mutex);
            _tp = new ThreadPool();
            _tp->Init();
            _tp->Start();
        }
        return _tp;
    }

    void Stop()
    {
        LockQueue();
        _isrunning = false;
        WakeUpAll();
        unLockQueue();
    }
    void Equeue(const T &in)
    {
        LockQueue();
        if (_isrunning)
        {
            LOG(DEBUG, "生产任务*1\n");
            _task_queue.push(in); // 生产任务
            //LOG(DEBUG, "_sleep_thread_num:%d\n", _sleep_thread_num);
            if (_sleep_thread_num > 0) /*如果有休眠的就唤醒*/
                WakeUp();
        }
        unLockQueue();
    }
    int TaskNum()
    {
        return _task_queue.size();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _thread_num;
    int _sleep_thread_num = 0;
    std::vector<Thread> _threads; // 线程池
    std::queue<T> _task_queue;    // 任务队列，生产者消费者模型
    bool _isrunning;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例模式
    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

// 类外初始化
template <typename T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;
